import Vue from 'vue'
import VueResource from 'vue-resource'

Vue.use(VueResource)

import config from '../../vue.config'

import themeArray from './themeArray'

// 封装一些全局元素。如全站通用功能函数和http请求等

export const global = {
  // 静态资源路径
  // staticPath: process.env.NODE_ENV !== 'development' ? config.build.staticPath : config.dev.staticPath,
  // 切换主题函数
  changeTheme: function(themeValue) {
    // var that = this
    // console.log('切换主题颜色值：', themeValue, that.staticPath, JSON.stringify(themeArray))
    var cssArray = themeArray
    if (themeValue === 'green') {
      for (let i = 0, len = cssArray.length; i < len; i++) {
        var itemPathRemove = config.assetsDir + '/theme/' + 'blue' + '/' + cssArray[i].toLowerCase() + '.css'
        removeCss(itemPathRemove)
        var itemPath = config.assetsDir + '/theme/' + themeValue + '/' + cssArray[i].toLowerCase() + '.css'
        loadCss(itemPath)
      }
    } else {
      for (let i = 0, len = cssArray.length; i < len; i++) {
        var itemPathRemove1 = config.assetsDir + '/theme/' + 'green' + '/' + cssArray[i].toLowerCase() + '.css'
        removeCss(itemPathRemove1)
        // for (let i = 0, len = cssArray.length; i < len; i++) {
        var itemPath1 = config.assetsDir + '/theme/' + themeValue + '/' + cssArray[i].toLowerCase() + '.css'
        loadCss(itemPath1)
        // }
      }
    }
    localStorage.setItem('themeValue', themeValue)

    function loadCss(path) {
      var head = document.getElementsByTagName('head')[0]
      var link = document.createElement('link')
      link.href = path
      link.rel = 'stylesheet'
      link.type = 'text/css'
      head.appendChild(link)
    }

    function removeCss(href) {
      // 清除动态添加的css文件
      // const links = document.getElementsByTagName('link')
      // const head = document.getElementsByTagName('head')[0]
      // const arr = []
      // if (links && links.length > 0) {
      //   for (let i = 0, len = links.length; i < len; i++) {
      //     if (links[i].href = href) {
      //       arr.push(links[i])
      //     }
      //   }
      //   for (let i = 0, len = arr.length; i < len; i++) {
      //     head.removeChild(arr[i])
      //   }
      // }
      // 清除动态添加的css文件
      // debugger
      var targetelement = 'link'
      var targetattr = 'href'
      var allsuspects = document.getElementsByTagName(targetelement)
      for (var i = allsuspects.length; i >= 0; i--) {
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(href) !== -1) {
          allsuspects[i].parentNode.removeChild(allsuspects[i])
        }
      }
    }
  }
}
